import _ from 'lodash'
import React, { useEffect, useRef, useState } from 'react'
const UsePaginatedHook =  (getApiList,pageSize=15,params)=> {
  const {come,state,searchKey} = params
  const [page,setPage]=useState(1)
  const [loading,setLoading]=useState(false)
  const [hasMore,setMore]=useState(true)
  const [list,setList]=useState([])
  const Intersection=useRef(null)
  useEffect(() => {
    if(hasMore){
      sendApi()
    }
  }, [page])
  useEffect(() => {
    setMore(true)
    setPage(1)
  }, [searchKey, come, state])
  useEffect(() => {
    console.log(list);
  },[list])
  const sendApi = async()=>{
    setLoading(true)
    const RES = await getApiList({page,pageSize,...params})
    setLoading(false)
    const totalCount = _.get(RES,'data.totalCount')
    setMore(Boolean(totalCount > (page * pageSize)))
    if(RES.code===200){
      const data = _.get(RES,'data.data')
      params.searchKey? setList(data):setList(pre=>[...pre,...data])
    }
  }
  const endRef = (dom) => {
    if(loading) return
    if(!hasMore) return
    if(Intersection.current) Intersection.current.disconnect();
    if(dom){
       Intersection.current = new IntersectionObserver((entries)=>{
        if(entries[0].isIntersecting){
          setPage(pre=>pre+1)
        }
      },{
        root: null,        // 默认监视视口（可指定父级容器）
        threshold: 0.8    // 目标元素完全进入视口时才触发
      })
      Intersection.current.observe(dom)  // 观察该元素
    }
  }
  return {
    endRef,
    list,
    setList
  };
}
export default UsePaginatedHook